﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using GraphViewer.Entity;
using GraphViewer.View;
using System.IO;
using System.Diagnostics;
using System.Configuration;
using System.Xml.Linq;
using System.Xml.Serialization;
using System.Xml;
using GraphViewer.Data;
using GraphViewer;
using System.Threading.Tasks;
using System.Threading;

namespace ExecutionOrder
{
    class Program
    {
        private static string _sqlServerName;
        private static string _mtsServerName;
        private static string _dataBase;
        private static bool _agendar;
        private static DataLoader _dataLoader = new DataLoader();

        static void Main(string[] args)
        {
            _sqlServerName = ConfigurationManager.AppSettings["SQLServerName"];
            _mtsServerName = ConfigurationManager.AppSettings["MTSServerName"];
            _agendar = Convert.ToBoolean(ConfigurationManager.AppSettings["Agendar"]);
            _dataBase = ConfigurationManager.AppSettings["DataBase"];

            _dataLoader.LoadData(_sqlServerName, "SRC");
            ChangeFrameworkClient();
            SelectGroups();
            ExecutionControl.Instance.Execute(_dataLoader, _mtsServerName, _dataBase);

            Console.WriteLine("Finalizado");
            Console.ReadKey();
        }

        private static void SelectGroups()
        {
            Console.Write("Digite o grupo(s):");
            string imput = Console.ReadLine();

            if (imput == "999")
            {
                Console.Write("Processo:");
                ExecutionControl.Instance.ProcessForceError = Console.ReadLine();

                Console.Write("Digite o grupo(s):");
                imput = Console.ReadLine();
            }

            if (imput == "666")
            {
                foreach (var group in _dataLoader.Groups)
                {
                    ExecutionControl.Instance.Groups.Add(group.GroupId);
                }
            }
            else
            {
                foreach (var g in imput.Split(','))
                {
                    ExecutionControl.Instance.Groups.Add(g);
                }
            }
        }

        private static void ChangeFrameworkClient()
        {
            string file = @"C:\FWKBBA\v2.0\Client\bba.framework.remote.client.dll.config";

            XDocument document = XDocument.Load(file);
            var element = XElement.Parse(string.Format("<chave sistema=\"RiscoCredito\" local=\"LOCAL\" valor=\"tcp://{0}:11333\" canal=\"tcp\" />", _mtsServerName));

            var node = document.Descendants().ToList().Find(e => e.Name.LocalName == "chave" && e.Attributes().Any(a => a.Name.LocalName == "sistema" && a.Value == "RiscoCredito"));
            node.Remove();

            var appSettings = document.Descendants().ToList().Find(e => e.Name.LocalName == "appSettings");
            appSettings.Add(element);

            document.Save(file);
        }

        private static void WriteProcessList(string groupId)
        {
            //if (File.Exists(@"c:\processos_grupo_" + groupId + ".bat"))
            //    File.Delete(@"c:\processos_grupo_" + groupId + ".bat");

            //if (File.Exists(@"c:\processos.bat"))
            //    File.Delete(@"c:\processos.bat");

            //foreach (var process in _orderedProcesses.Where(p => p.GroupId == groupId && p.TaskType == "Job"))
            //{

            //    //File.AppendAllText(@"c:\processos_grupo_" + groupId + ".txt", process.ProcessId + System.Environment.NewLine);
            //    //File.AppendAllText(@"c:\processos_grupo_" + groupId + ".txt", process.ProcessId.ToString().PadRight(10) + process.ProcessName.ToString() + System.Environment.NewLine);
            //    //File.AppendAllText(@"c:\processos_grupo_" + groupId + ".txt", process.GroupId.ToString().PadRight(10) + process.ProcessId.ToString().PadRight(10) + Environment.NewLine);
            //    File.AppendAllText(@"c:\processos_grupo_" + groupId + ".bat", @"\\" + _mtsServerName + @"\Componentes\dotnet\SRC\ibba.src.console.exe -servidor:" + _mtsServerName + " -tipo:comando -id:" + process.ProcessId + " -ref:" + _dataBase + System.Environment.NewLine);
            //    //File.AppendAllText(@"c:\processos_grupo_" + groupId + ".txt", @"\\BBAGMMTSATI1\Componentes\dotnet\SRC\ibba.src.console.exe -servidor:BBAGMMTSATI1 -tipo:comando -id:" + process.ProcessId + " -ref:" + _dataBase + System.Environment.NewLine);
            //    //File.AppendAllText(@"c:\processos_grupo_" + groupId + ".bat", "pause" + System.Environment.NewLine);
            //    //File.AppendAllText(@"c:\processos_grupo_" + groupId + ".bat", System.Environment.NewLine);
            //    //File.AppendAllText(@"c:\processos.txt", process.GroupId.ToString().PadRight(10) + process.ProcessId.ToString().PadRight(10) + Environment.NewLine);
            //}
        }

        private void WriteProcess(List<int> processes, XElement jobNode)
        {
            //int processId = 0;
            //string processName = FindProcessId(jobNode);
            //int.TryParse(processName, out processId);

            //if (processId != 0 && processes.Find(p => p == processId) == 0)
            //{
            //    processes.Add(processId);

            //    File.AppendAllText(@"c:\processo.txt", processId + System.Environment.NewLine);
            //}
        }

        private void OrderControlMXml(string fileName, List<XElement> elements)
        {
            //XDocument orderedDocument = XDocument.Load(fileName);

            //var tableElement = orderedDocument.Descendants().Where(n => n.Name.LocalName == "SCHED_TABLE").First();

            //tableElement.RemoveNodes();

            //foreach (var process in _processesControlM)
            //{
            //    if (process.Predecessors.Count > 0)
            //    {
            //        OrderProcesses(process);
            //    }
            //}

            //foreach (var process in _orderedProcessesSimio)
            //{
            //    var jobName = elements.Find(n => n.Attribute("JOBNAME").Value.ToString() == process.ProcessId);

            //    tableElement.Add(jobName);
            //}

            //orderedDocument.Save(@"c:\teste\a.xml");
        }

        private void ListAllJobs(XDocument document)
        {
            var jobs = (from n in document.Descendants()
                        where n.Name.LocalName == "JOB"
                        select new { JobName = n.Attribute("JOBNAME").Value, Description = n.Attribute("DESCRIPTION").Value }).Distinct().OrderBy(j => j.JobName);

            foreach (var item in jobs)
            {
                File.AppendAllText(@"c:\teste\jobs.txt", item.JobName + "|" + item.Description + System.Environment.NewLine);
            }
        }
    }
}
